package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cache.annotation.CacheUsing;
import com.event.util.EventUtil;
import com.qf.dao.HotalDao;
import com.qf.entity.*;
import com.qf.feign.CityFeign;
import com.qf.feign.SearchFeign;
import com.qf.service.HotalService;
import com.qf.service.RoomPriceService;
import com.qf.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * (Hotal)表服务实现类
 *
 * @author makejava
 * @since 2020-09-14 14:34:31
 */
@Service("hotalService")
public class HotalServiceImpl extends ServiceImpl<HotalDao, Hotal> implements HotalService {

    @Autowired
    private RoomService roomService;

    @Autowired
    private RoomPriceService roomPriceService;

    @Autowired
    private SearchFeign searchFeign;

    @Autowired
    private EventUtil eventUtil;

    @Autowired
    private CityFeign cityFeign;

    /**
     * 查询酒店列表
     * @return
     */
    @Override
    public List<Hotal> list() {
        //酒店列表
        List<Hotal> hotals = super.list();

        //循环酒店列表
        hotals.stream().forEach(hotal -> {
            //搜索酒店下的客房信息
            List<Room> rooms = roomService.list(new QueryWrapper<Room>().eq("hid", hotal.getId()));

            //查询房间的价格信息
            rooms.stream().forEach(room -> {
                //价格列表
                List<RoomPrice> roomPrices = roomPriceService.list(new QueryWrapper<RoomPrice>().eq("rid", room.getId()));
                //设置给客房
                room.setPrices(roomPrices);
            });

            //客房信息保存到酒店对象中
            hotal.setRooms(rooms);
        });

        return hotals;
    }

    /**
     * 新增酒店
     * @param entity
     * @return
     */
    @Override
    public boolean save(Hotal entity) {
        //保存酒店信息到数据库
        boolean flag = super.save(entity);

        //将酒店信息同步到ES中
//        searchFeign.syncHotal(entity);

        //发布一个酒店新增的消息（所有订阅者都会收到）
        eventUtil.publishEvent("hotal_insert", entity);
        return flag;
    }

    @Override
    @CacheUsing(key = "'hotal_' + #id")
    public Hotal getById(Serializable id) {
        System.out.println("查询酒店的详情信息！！！！！！");
        //获得酒店信息
        Hotal hotal = super.getById(id);

        //获取城市信息
        R<City> cityR = cityFeign.queryCity(hotal.getCid());
        hotal.setCity(cityR.getData());

        //查询客房信息
        List<Room> rooms = roomService.list(new QueryWrapper<Room>().eq("hid", hotal.getId()));
        hotal.setRooms(rooms);

        //查询客房的价格信息
        rooms.stream().forEach(room -> {

            //获得房间的价格列表
            List<RoomPrice> priceList = roomPriceService.list(new QueryWrapper<RoomPrice>().eq("rid", room.getId()));
            room.setPrices(priceList);
        });

        return hotal;
    }
}